package com.xuyuan.concurrent.test;

public class ThreadLocalDemo {
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        // 创建并启动两个线程
        Thread thread1 = new Thread(new MyRunnable(), "thread1");
        Thread thread2 = new Thread(new MyRunnable(), "thread2");
        thread1.start();
        thread2.start();
    }

    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            // 在当前线程中设置 ThreadLocal 变量的值
            threadLocal.set((int) (Math.random() * 100));
            System.out.println("ThreadLocal value in thread " + Thread.currentThread().getName() + ": " + threadLocal.get());

            // 模拟业务逻辑的处理过程
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 再次获取 ThreadLocal 变量的值
            System.out.println("ThreadLocal value in thread " + Thread.currentThread().getName() + ": " + threadLocal.get());

            // 清除 ThreadLocal 变量的值
            threadLocal.remove();
            System.out.println("ThreadLocal value after removal in thread " + Thread.currentThread().getName() + ": " + threadLocal.get());
        }
    }
}